package org.bing.flex.action {

    import mx.messaging.ChannelSet;
    import mx.messaging.channels.AMFChannel;
    import mx.rpc.AsyncToken;
    import mx.rpc.remoting.mxml.Operation;
    import mx.rpc.remoting.mxml.RemoteObject;

    public class RemoteDelegate {

        private static var cache:Object=new Object();

        public function invoke(url:String, remoteObjectName:String, operationName:String, args:Object=null, onResult:Function=null, showLoading:Boolean=false):void {
            var key:String=remoteObjectName + "-" + operationName;
            var operation:Operation=cache[key] as Operation;
            if (operation == null) {
                var ro:RemoteObject=new RemoteObject(remoteObjectName);
                if (url != null) {
                    var endpoint:String=url;
                    var chan:AMFChannel=new AMFChannel("amfOnHttp", endpoint);
                    var channelSet:ChannelSet=new ChannelSet();
                    channelSet.addChannel(chan);
                    ro.channelSet=channelSet;
                }

                operation=ro.getOperation(operationName) as Operation;
                cache[key]=operation;
            }
            if (args) {
                operation.arguments=(args is Array) ? args : [args];
            }

            var responder:RemoteResponder=new RemoteResponder(null, onResult, null, showLoading);
            var caller:AsyncToken=operation.send();
            caller.addResponder(responder);
        }
    }
}